package com.example.learnvideo.ui

import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.net.wifi.ScanResult
import android.net.wifi.WifiConfiguration
import android.net.wifi.WifiManager
import android.os.Handler
import android.os.Looper
import android.widget.CompoundButton
import android.widget.LinearLayout
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.learnvideo.adapter.WifiListAdapter
import com.example.learnvideo.base.BaseActivity
import com.example.learnvideo.bean.WifiConnect
import com.example.learnvideo.databinding.ActivityWifiConnectBinding
import com.example.learnvideo.util.Utils
import com.example.learnvideo.widget.InputDialogFragment
import java.util.*
import kotlin.collections.ArrayList

class WifiConnectActivity : BaseActivity<ActivityWifiConnectBinding>(),CompoundButton.OnCheckedChangeListener,InputDialogFragment.InputCallbacks {

    private lateinit var mWifiManager:WifiManager
    private val mHandler = Handler(Looper.getMainLooper())

    override fun ActivityWifiConnectBinding.initBinding() {
        //LayoutManager用于指定RecyclerView的布局方式，
        // 这里使用的LinearLayoutManager是线性布局的意思
        val linearLayout = LinearLayoutManager(this@WifiConnectActivity)
        rvWifi.layoutManager = linearLayout
        if (Utils.getWlanStatus(this@WifiConnectActivity)){
            ckWlan.isChecked = true
        }
        ckWlan.setOnCheckedChangeListener(this@WifiConnectActivity)
        mWifiManager = applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
        mHandler.postDelayed(object :Runnable{
            override fun run() {
                scanWifiList()
                mHandler.postDelayed(this,3000)
            }
        },50)
    }

    override fun onCheckedChanged(buttonView: CompoundButton?, isChecked: Boolean) {
        if (buttonView?.id == mBinding.ckWlan.id){
            Utils.setWlanStatus(this,isChecked)
        }
    }

    private fun scanWifiList(){
        val wifiList = ArrayList<WifiConnect>()
        val wifiInfo = mWifiManager.connectionInfo
        val state = mWifiManager.wifiState
        var ssid = ""
        if (state == WifiManager.WIFI_STATE_ENABLED || state == WifiManager.WIFI_STATE_ENABLING){
            ssid = wifiInfo.ssid
        }else{
            val wifiAdapter = WifiListAdapter(this,mWifiManager,wifiList)
            mBinding.rvWifi.adapter = wifiAdapter
            return
        }
        mWifiManager.startScan()
        val resultList = getResultList()
        if (ActivityCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_FINE_LOCATION
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            ActivityCompat.requestPermissions(this, arrayOf(
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.ACCESS_FINE_LOCATION,
            ),1)
        }
        val mConfigList = mWifiManager.configuredNetworks
        for(i in resultList.indices){
            val item = resultList[i]
            val wifi = WifiConnect()
            wifi.ssid = item.SSID
            wifi.level = WifiManager.calculateSignalLevel(item.level,4)
            if (ssid.indexOf(wifi.ssid) >= 0){
                wifi.status = true
            }
            if (item.capabilities.toUpperCase(Locale.getDefault()).indexOf("WPA2") >= 0){
                wifi.type = 4
            }else if (item.capabilities.toUpperCase(Locale.getDefault()).indexOf("WPA") >= 0){
                wifi.type = WifiConfiguration.KeyMgmt.WPA_PSK
            }else{
                wifi.type = WifiConfiguration.KeyMgmt.NONE
            }
            for (j in mConfigList.indices){
                if (mConfigList[j].SSID.indexOf(wifi.ssid) >= 0){
                    wifi.networkId = mConfigList[j].networkId
                    break
                }
            }
            wifiList.add(wifi)
        }
        val wifiAdapter = WifiListAdapter(this,mWifiManager,wifiList)
        mBinding.rvWifi.adapter = wifiAdapter
    }

    private fun getResultList():ArrayList<ScanResult>{
        val resultList = mWifiManager.scanResults
        val newResultList = ArrayList<ScanResult>()
        for (i in resultList.indices){
            val item = resultList[i]
            var j = 0
            for (k in newResultList.indices){
                j++
                val newItem = newResultList[k]
                if (item.SSID.equals(newItem.SSID)){
                    if (item.level > newItem.level){
                        newResultList.set(j,item)
                    }
                    break
                }
            }
            if (j >= newResultList.size){
                newResultList.add(item)
            }
        }
        return newResultList
    }

    override fun onInput(SSID: String, password: String, type: Int) {
        val config = createWifiInfo(SSID,password,type)
        val netId = mWifiManager.addNetwork(config)
        if (netId == -1){
            Toast.makeText(this,"密码错误",Toast.LENGTH_SHORT).show()
        }else{
            mWifiManager.enableNetwork(netId,true)
        }
    }

    //创建新的WiFi配置信息，内含用户名、密码、加密类型等信息
    private fun createWifiInfo(ssid:String,password: String,type:Int):WifiConfiguration{
        val config = WifiConfiguration()
        config.SSID = "\"${ssid}\""
        if (type != WifiConfiguration.KeyMgmt.NONE){ //明文密码
            config.wepKeys[0] = ""
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE)
            config.wepTxKeyIndex = 0
        } else { // WPA加密或者WPA2加密
            config.preSharedKey = "\"${password}\""
            config.hiddenSSID = true
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN)
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP)
            config.allowedKeyManagement.set(type)
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP)
            config.allowedProtocols.set(WifiConfiguration.Protocol.WPA)
            config.status = WifiConfiguration.Status.ENABLED
        }
        return config
    }
}